<?php
namespace app\api\controller;

use think\Request;
use app\api\controller\ApiBase;

class Upload extends ApiBase
{
    public function uploadImage()
    {
        // 获取表单上传文件
        $file = Request::instance()->file('files');

        // 移动到服务器的上传目录 /home/www/upload/
        $path = ROOT_PATH . 'upload' . DS . 'image';
        $info = $file->move($path);
        
        if(!empty($info)){
            // 成功上传后 获取上传信息
            //echo $info->getExtension(); // 输出 jpg
            //echo $info->getFilename(); // 输出 42a79759f284b767dfcb2a0197904287.jpg
            $data['pathDate'] = date('Ymd',time());//$info->getPath();
            $data['fileName'] = $info->getFilename();
            $data['saveName'] = 'upload/image/' . str_replace('\\', '/', $info->getSaveName());
            $msg = '上传成功';
            $code = 200;
        }else{
            // 上传失败获取错误信息
            $code = 201;
            $msg = $file->getError();

        }

        return $this->response($code, $msg, $data);
    }

    public function removeImage()
    {
        $imageUrl = Request::instance()->param('key');
        $id       = Request::instance()->param('id');
        $model    = Request::instance()->param('model');
        $clear    = false;

        // 删除数据库中图片路径 
        switch ($model) {
            case 'article':
                $clear = \app\common\model\Article::setImage($id , '');
                break;
            case 'user':
                $clear = \app\common\model\User::setAvatar($id , '');
                break;
            case 'slider':
                $clear = \app\common\model\Slider::setImage($id , '');
                break;
            case 'water':
                $water = json_decode(\app\common\model\Config::getValue('water'), true);
                $water['logo'] = '';
                $clear = \app\common\model\Config::setValue('water', json_encode($water));
                break;
        }

        $paras = str_replace(getDomain(), "", $imageUrl);
        $file = ROOT_PATH . ltrim($paras, '/');

        // 删除物理图片
        if (is_file($file)) {
            unlink($file);
        }

        // 返回信息
        if($clear != false && $file){
            return $this->response(200);
        }else{
           return $this->response(201);
        }
    }
}
